package binarytree;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 14:13
 * https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/submissions/
 * 给定一个二叉树，找出其最大深度。
 */
public class MaxDepth {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Node {
        int val;
        List<Node> children;

        public Node() {
        }

        public Node(int val, List<Node> children) {
            this.val = val;
            this.children = children;
        }
    }


    /**
     * 二叉树层次遍历
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        int max = 0;
        Queue<TreeNode> levelNodes = new LinkedList<>();
        if (root != null) {
            levelNodes.offer(root);
        }
        while (!levelNodes.isEmpty()) {
            max++;
            int size = levelNodes.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = levelNodes.poll();
                if (poll.left != null) {
                    levelNodes.offer(poll.left);
                }
                if (poll.right != null) {
                    levelNodes.offer(poll.right);
                }
            }
        }
        return max;
    }

    /**
     * N叉树层次遍历
     * @param root
     * @return
     */
    public int maxDepthN(Node root) {
        int max = 0;
        Queue<Node> levelNodes = new LinkedList<>();
        if (root != null) {
            levelNodes.offer(root);
        }
        while (!levelNodes.isEmpty()) {
            max++;
            int size = levelNodes.size();
            for (int i = 0; i < size; i++) {
                Node poll = levelNodes.poll();
                levelNodes.addAll(poll.children);
            }
        }
        return max;
    }

    /**
     * 二叉树dfs  根节点的高度就是二叉树的最大深度
     * @param root
     * @return
     */
    public int maxDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int maxleftlen = maxDepth1(root.left);
        int maxrightlen = maxDepth1(root.right);
        return Math.max(maxleftlen, maxrightlen) + 1;
    }

    /**
     * N叉树dfs
     * @param root
     * @return
     */
    public int maxDepth1N(Node root) {
        if (root == null) {
            return 0;
        }
        //当节点没有孩子时，深度为0
        int maxChildrenLen = 0;
        for (Node node : root.children) {
            maxChildrenLen = Math.max(maxChildrenLen, maxDepth1N(node));
        }
        return maxChildrenLen + 1;
    }

    public static void main(String[] args) {

    }
}
